<template>
  <q-dialog v-model="isVisible" persistent>
    <q-card class="check-updates-dialog">
      <q-card-section class="row items-center q-pb-none">
        <div class="text-h6">{{ t('rt.checkUpdates') }}</div>
        <q-space />
        <q-btn
          icon="refresh"
          flat
          round
          dense
          :loading="loading"
          @click="fetchReleases"
          :disable="loading"
        />
        <q-btn icon="close" flat round dense v-close-popup />
      </q-card-section>

      <q-card-section class="q-pt-none">
        <div v-if="loading" class="text-center q-pa-md">
          <q-spinner-dots color="primary" size="40px" />
          <div class="q-mt-sm">{{ $t('rt.checkingUpdates') }}</div>
          <div class="text-caption text-grey-6 q-mt-xs">Loading...</div>
        </div>

        <div v-else-if="error" class="text-center q-pa-md">
          <q-icon name="error" color="negative" size="40px" />
          <div class="q-mt-sm text-negative">{{ error }}</div>
          <q-btn
            :label="$t('retry')"
            color="primary"
            class="q-mt-md"
            @click="fetchReleases"
          />
        </div>

        <div v-else-if="releases.length === 0" class="text-center q-pa-md">
          <q-icon name="info" color="info" size="40px" />
          <div class="q-mt-sm">{{ $t('rt.noUpdatesAvailable') }}</div>
        </div>

        <div v-else>
          <q-table
            :rows="releases"
            :columns="columns"
            row-key="id"
            :pagination="{ rowsPerPage: 10 }"
            class="updates-table"
          >
            <template v-slot:body-cell-update="props">
              <q-td :props="props">
                <q-btn
                  :label="$t('update')"
                  color="primary"
                  size="sm"
                  @click="updateApp(props.row.assets[0]?.browser_download_url)"
                />
              </q-td>
            </template>
          </q-table>
        </div>
      </q-card-section>
    </q-card>
  </q-dialog>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, computed } from 'vue';
import { useI18n } from 'vue-i18n';
import NativeFunction from '../utils/NativeFunction';

const { t } = useI18n();

interface ReleaseAsset {
  browser_download_url: string;
  name: string;
}

interface Release {
  id: number;
  tag_name: string;
  name: string;
  body: string;
  assets: ReleaseAsset[];
  created_at: string;
}

const props = defineProps<{
  modelValue: boolean
}>();

const emit = defineEmits<{
  'update:modelValue': [value: boolean]
}>();

const isVisible = ref(props.modelValue);
const loading = ref(false);
const error = ref('');
const releases = ref<Release[]>([]);
const lastFetchTime = ref(0);
const cacheExpiry = 5 * 60 * 1000; // 5分钟缓存

// 检查是否需要重新获取数据
const shouldFetchData = () => {
  const now = Date.now();
  return releases.value.length === 0 || (now - lastFetchTime.value) > cacheExpiry;
};

// 表格列定义
const columns = computed(() => [
  {
    name: 'update',
    label: t('update'),
    field: 'update',
    align: 'center' as const,
    sortable: false
  },
  {
    name: 'created_at',
    label: t('releaseAt') || '发布时间',
    field: 'created_at',
    align: 'left' as const,
    sortable: true,
    format: (val: string) => {
      if (!val) return '';
      try {
        const date = new Date(val);
        return date.toLocaleString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit',
          hour12: false
        }).replace(/\//g, '-');
      } catch {
        return val;
      }
    }
  },
  {
    name: 'tag_name',
    label: t('version'),
    field: 'tag_name',
    align: 'left' as const,
    sortable: true
  },
  {
    name: 'name',
    label: t('versionName'),
    field: 'name',
    align: 'left' as const,
    sortable: true
  }
]);

// 监听 modelValue 变化
watch(() => props.modelValue, (newVal) => {
  isVisible.value = newVal;
  if (newVal && shouldFetchData()) {
    fetchReleases();
  }
});

// 监听 isVisible 变化
watch(isVisible, (newVal) => {
  emit('update:modelValue', newVal);
});

// 获取版本信息
const fetchReleases = async () => {
  loading.value = true;
  error.value = '';

  try {
    // 添加超时控制
    const controller = new AbortController();
    const timeoutId = setTimeout(() => controller.abort(), 10000); // 10秒超时

    const response = await fetch('https://gitee.com/api/v5/repos/sklef/lcc-world-model7-android/releases', {
      signal: controller.signal
    });

    clearTimeout(timeoutId);

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    const data = await response.json();
    // 按创建时间排序，最新的在最前面
    releases.value = (data || []).sort((a: Release, b: Release) => {
      const dateA = new Date(a.created_at || 0);
      const dateB = new Date(b.created_at || 0);
      return dateB.getTime() - dateA.getTime();
    });
    lastFetchTime.value = Date.now();
  } catch (err) {
    console.error('获取版本信息失败:', err);
    if (err.name === 'AbortError') {
      error.value = '请求超时，请检查网络连接';
    } else {
      error.value = err instanceof Error ? err.message : '获取版本信息失败';
    }
  } finally {
    loading.value = false;
  }
};

// 更新应用
const updateApp = (downloadUrl: string) => {
  if (!downloadUrl) {
    console.error('下载链接无效');
    return;
  }

  try {
    // 调用 jsInterface 的更新方法
    NativeFunction.updateAppVersionByUrl(downloadUrl);
  } catch (err) {
    LCC.msg('update failed: ' + err, { type: 'error' });
  }
};

onMounted(() => {
  if (isVisible.value && shouldFetchData()) {
    fetchReleases();
  }
});
</script>

<style lang="less" scoped>
.check-updates-dialog {
  min-width: 600px;
  max-width: 90vw;
  max-height: 80vh;
}

.updates-table {
  max-height: 400px;
}

/* 移动端适配 */
@media (max-width: 768px) {
  .check-updates-dialog {
    min-width: 90vw;
    max-width: 95vw;
    margin: 8px;
  }

  .updates-table {
    max-height: 300px;
  }

  :deep(.q-table) {
    font-size: 12px;
  }

  :deep(.q-table th) {
    padding: 4px;
  }

  :deep(.q-table td) {
    padding: 4px;
  }
}

@media (max-width: 480px) {
  .check-updates-dialog {
    min-width: 95vw;
    max-width: 98vw;
    margin: 4px;
  }

  .updates-table {
    max-height: 250px;
  }
}
</style>
